// 获取画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 游戏变量
// 使用AudioContext生成音效
class SoundEffects {
    constructor() {
        this.audioContext = null;
        // 尝试初始化AudioContext
        this.initAudioContext();
    }

    initAudioContext() {
        try {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            this.audioContext = new AudioContext();
            console.log('AudioContext initialized successfully');
        } catch (e) {
            console.error('Failed to initialize AudioContext:', e);
        }
    }

    // 播放跳跃音效
    playJumpSound() {
        console.log('Attempting to play jump sound');
        if (!this.audioContext) {
            console.log('AudioContext not initialized, trying to initialize...');
            this.initAudioContext();
            if (!this.audioContext) {
                console.error('Failed to initialize AudioContext for jump sound');
                return;
            }
        }

        try {
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();

            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(440, this.audioContext.currentTime);
            oscillator.frequency.exponentialRampToValueAtTime(220, this.audioContext.currentTime + 0.2);

            gainNode.gain.setValueAtTime(0.5, this.audioContext.currentTime); // 增加音量
            gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.2);

            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);

            oscillator.start();
            oscillator.stop(this.audioContext.currentTime + 0.2);
            console.log('Jump sound played successfully');
        } catch (e) {
            console.error('Error playing jump sound:', e);
        }
    }

    // 播放金币音效
    playCoinSound() {
        console.log('Attempting to play coin sound');
        if (!this.audioContext) {
            console.log('AudioContext not initialized, trying to initialize...');
            this.initAudioContext();
            if (!this.audioContext) {
                console.error('Failed to initialize AudioContext for coin sound');
                return;
            }
        }

        try {
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();

            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(880, this.audioContext.currentTime);
            oscillator.frequency.exponentialRampToValueAtTime(440, this.audioContext.currentTime + 0.1);

            gainNode.gain.setValueAtTime(0.5, this.audioContext.currentTime); // 增加音量
            gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.1);

            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);

            oscillator.start();
            oscillator.stop(this.audioContext.currentTime + 0.1);
            console.log('Coin sound played successfully');
        } catch (e) {
            console.error('Error playing coin sound:', e);
        }
    }

    // 播放胜利音效
    playWinSound() {
        console.log('Attempting to play win sound');
        if (!this.audioContext) {
            console.log('AudioContext not initialized, trying to initialize...');
            this.initAudioContext();
            if (!this.audioContext) {
                console.error('Failed to initialize AudioContext for win sound');
                return;
            }
        }

        try {
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();

            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(523.25, this.audioContext.currentTime);
            oscillator.frequency.setValueAtTime(659.25, this.audioContext.currentTime + 0.2);
            oscillator.frequency.setValueAtTime(783.99, this.audioContext.currentTime + 0.4);

            gainNode.gain.setValueAtTime(0.5, this.audioContext.currentTime); // 增加音量
            gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.6);

            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);

            oscillator.start();
            oscillator.stop(this.audioContext.currentTime + 0.6);
            console.log('Win sound played successfully');
        } catch (e) {
            console.error('Error playing win sound:', e);
        }
    }

    // 播放失败音效
    playLoseSound() {
        console.log('Attempting to play lose sound');
        if (!this.audioContext) {
            console.log('AudioContext not initialized, trying to initialize...');
            this.initAudioContext();
            if (!this.audioContext) {
                console.error('Failed to initialize AudioContext for lose sound');
                return;
            }
        }

        try {
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();

            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(220, this.audioContext.currentTime);
            oscillator.frequency.exponentialRampToValueAtTime(110, this.audioContext.currentTime + 0.5);

            gainNode.gain.setValueAtTime(0.5, this.audioContext.currentTime); // 增加音量
            gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.5);

            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);

            oscillator.start();
            oscillator.stop(this.audioContext.currentTime + 0.5);
            console.log('Lose sound played successfully');
        } catch (e) {
            console.error('Error playing lose sound:', e);
        }
    }
}

// 创建音效实例
const soundEffects = new SoundEffects();

// 游戏变量
let score = 0;
const scoreElement = document.getElementById('score');
let timeLeft = 30; // 30秒时间限制
const timeElement = document.getElementById('time');
let targetScore = 10; // 目标分数
const targetScoreElement = document.getElementById('targetScore');
let gameOver = false;
let gameStarted = false;
let coinSpeed = 3; // 金币移动速度
let coinSpawnRate = 100; // 金币生成速率
let gravity = 0.8; // 重力
let difficulty = 'medium'; // 默认难度

// 玩家对象
const player = {
    x: 50,
    y: 300,
    width: 50,
    height: 50,
    speed: 5,
    jumpPower: 25,
    velocityY: 0,
    isJumping: false,
    color: '#ff6b6b'
};

// 金币数组
let coins = [];
const coinWidth = 30;
const coinHeight = 30;
const coinColor = '#ffd166';
let frameCount = 0;

// 键盘控制
const keys = {
    left: false,
    right: false,
    up: false
};

// 监听键盘事件
document.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowLeft') keys.left = true;
    if (e.key === 'ArrowRight') keys.right = true;
    if (e.key === 'ArrowUp' && !player.isJumping) {
        player.velocityY = -player.jumpPower;
        player.isJumping = true;
        soundEffects.playJumpSound();
    }
});

document.addEventListener('keyup', (e) => {
    if (e.key === 'ArrowLeft') keys.left = false;
    if (e.key === 'ArrowRight') keys.right = false;
});

// 生成金币
function spawnCoin() {
    const x = canvas.width;
    const y = Math.random() * (canvas.height - 200) + 50;
    coins.push({ x, y });
}

// 检测碰撞
function checkCollision(player, coin) {
    return player.x < coin.x + coinWidth &&
           player.x + player.width > coin.x &&
           player.y < coin.y + coinHeight &&
           player.y + player.height > coin.y;
}

// 更新游戏状态
function update() {
    if (gameOver) return;

    // 更新时间
    if (gameStarted) {
        // 每60帧减少1秒（假设60fps）
        if (frameCount % 60 === 0) {
            timeLeft--;
            timeElement.textContent = timeLeft;

            // 检查时间是否用完
            if (timeLeft <= 0) {
                showGameResult(score >= targetScore);
                // 播放失败音效
                if (score < targetScore) {
                    console.log('Playing lose sound - score:', score, 'target:', targetScore);
                    soundEffects.playLoseSound();
                } else {
                    console.log('Not playing lose sound - score meets target');
                }
                gameOver = true;
                return;
            }
        }
    }
    // 绘制渐变背景
    const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
    gradient.addColorStop(0, '#87CEEB');
    gradient.addColorStop(1, '#e0f7fa');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制地面
    ctx.fillStyle = '#8BC34A';
    ctx.fillRect(0, canvas.height - 50, canvas.width, 50);

    // 绘制简单的云朵背景
    drawClouds();

    // 更新玩家位置
    if (keys.left && player.x > 0) player.x -= player.speed;
    if (keys.right && player.x < canvas.width - player.width) player.x += player.speed;

    // 应用重力
    player.velocityY += gravity;
    player.y += player.velocityY;

    // 地面碰撞
    if (player.y > canvas.height - player.height) {
        player.y = canvas.height - player.height;
        player.velocityY = 0;
        player.isJumping = false;
    }

    // 生成金币
    frameCount++;
    if (frameCount % coinSpawnRate === 0) {
        spawnCoin();
    }

    // 更新金币位置并检测碰撞
    for (let i = coins.length - 1; i >= 0; i--) {
        coins[i].x -= coinSpeed; // 金币向左移动

        // 检测碰撞
        if (checkCollision(player, coins[i])) {
            score++;
            scoreElement.textContent = score;
            coins.splice(i, 1);
            soundEffects.playCoinSound();

            // 检查是否达到目标分数
            if (score >= targetScore) {
                showGameResult(true);
            soundEffects.playWinSound();
            gameOver = true;
            return;
            }
        }

        // 移除屏幕外的金币
        if (coins[i] && coins[i].x + coinWidth < 0) {
            coins.splice(i, 1);
        }
    }

    // 绘制玩家
    ctx.fillStyle = player.color;
    ctx.beginPath();
    ctx.arc(player.x + player.width/2, player.y + player.height/2, player.width/2, 0, Math.PI * 2);
    ctx.fill();

    // 玩家眼睛
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.arc(player.x + player.width/3, player.y + player.height/3, player.width/8, 0, Math.PI * 2);
    ctx.arc(player.x + 2*player.width/3, player.y + player.height/3, player.width/8, 0, Math.PI * 2);
    ctx.fill();

    // 玩家瞳孔
    ctx.fillStyle = 'black';
    ctx.beginPath();
    ctx.arc(player.x + player.width/3, player.y + player.height/3, player.width/16, 0, Math.PI * 2);
    ctx.arc(player.x + 2*player.width/3, player.y + player.height/3, player.width/16, 0, Math.PI * 2);
    ctx.fill();

    // 绘制金币
    coins.forEach((coin, index) => {
        // 金币主体
        ctx.fillStyle = coinColor;
        ctx.beginPath();
        ctx.arc(coin.x + coinWidth/2, coin.y + coinHeight/2, coinWidth/2, 0, Math.PI * 2);
        ctx.fill();

        // 金币光泽
        ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
        ctx.beginPath();
        ctx.arc(coin.x + coinWidth/3, coin.y + coinHeight/3, coinWidth/6, 0, Math.PI * 2);
        ctx.fill();

        // 金币旋转动画
        ctx.save();
        ctx.translate(coin.x + coinWidth/2, coin.y + coinHeight/2);
        ctx.rotate(frameCount * 0.02 + index * 0.5);
        ctx.fillStyle = 'rgba(255, 210, 102, 0.7)';
        ctx.fillRect(-coinWidth/6, -coinHeight/2, coinWidth/3, coinHeight);
        ctx.restore();
    });

    // 绘制水印
    ctx.font = '14px Arial';
    ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
    ctx.textAlign = 'center';
    ctx.fillText('由吴瑾睿设计开发', canvas.width / 2, canvas.height - 10);

    // 如果游戏未结束，继续请求下一帧
    if (!gameOver) {
        requestAnimationFrame(update);
    }
}

// 更新难度设置
function updateDifficulty() {
    const difficultySelect = document.getElementById('difficulty');
    difficulty = difficultySelect.value;
    
    switch(difficulty) {
        case 'easy':
            timeLeft = 40;
            targetScore = 8;
            coinSpeed = 2;
            coinSpawnRate = 120;
            gravity = 0.7;
            break;
        case 'medium':
            timeLeft = 30;
            targetScore = 10;
            coinSpeed = 3;
            coinSpawnRate = 100;
            gravity = 0.8;
            break;
        case 'hard':
            timeLeft = 20;
            targetScore = 15;
            coinSpeed = 4;
            coinSpawnRate = 80;
            gravity = 0.9;
            break;
    }
    
    if (targetScoreElement) {
        targetScoreElement.textContent = targetScore;
    }
}

// 停止游戏
function stopGame() {
    gameOver = true;
    gameStarted = false;
}

// 开始游戏
function startGame() {
    score = 0;
    updateDifficulty(); // 应用当前难度设置
    gameOver = false;
    gameStarted = true;
    scoreElement.textContent = score;
    timeElement.textContent = timeLeft;
    targetScoreElement.textContent = targetScore;
    coins = [];
    frameCount = 0;
    update();
}

// 绘制云朵
function drawClouds() {
    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
    // 云朵1
    drawCloud(100, 80, 60);
    // 云朵2
    drawCloud(300, 120, 80);
    // 云朵3
    drawCloud(500, 60, 70);
    // 云朵4
    drawCloud(700, 100, 50);
}

// 绘制单个云朵
function drawCloud(x, y, size) {
    ctx.beginPath();
    ctx.arc(x, y, size/2, 0, Math.PI * 2);
    ctx.arc(x + size/2, y - size/4, size/3, 0, Math.PI * 2);
    ctx.arc(x + size, y, size/2, 0, Math.PI * 2);
    ctx.arc(x + size/2, y + size/4, size/3, 0, Math.PI * 2);
    ctx.fill();
}

// 显示游戏结果
function showGameResult(isSuccess) {
    // 创建结果显示元素
    const resultElement = document.createElement('div');
    resultElement.style.position = 'absolute';
    resultElement.style.top = '50%';
    resultElement.style.left = '50%';
    resultElement.style.transform = 'translate(-50%, -50%) scale(0.8)';
    resultElement.style.opacity = '0';
    resultElement.style.transition = 'all 0.5s ease';
    resultElement.style.backgroundColor = isSuccess ? 'rgba(76, 175, 80, 0.9)' : 'rgba(244, 67, 54, 0.9)';
    resultElement.style.color = 'white';
    resultElement.style.padding = '20px';
    resultElement.style.borderRadius = '20px';
    resultElement.style.fontSize = '20px';
    resultElement.style.textAlign = 'center';
    resultElement.style.zIndex = '100';
    resultElement.style.boxShadow = '0 15px 30px rgba(0,0,0,0.2)';
    resultElement.style.width = '80%';
    resultElement.style.maxWidth = '400px';

    // 添加到页面后触发动画
    document.body.appendChild(resultElement);
    setTimeout(() => {
        resultElement.style.transform = 'translate(-50%, -50%) scale(1)';
        resultElement.style.opacity = '1';
    }, 10);

    // 设置结果文本
    if (isSuccess) {
        resultElement.innerHTML = `恭喜你！<br>达到了目标分数 ${targetScore}<br>你的分数: ${score}`;
    } else {
        resultElement.innerHTML = `游戏结束！<br>未达到目标分数 ${targetScore}<br>你的分数: ${score}`;
    }

        // 添加按任意键继续提示
    const continuePrompt = document.createElement('p');
    continuePrompt.textContent = '按任意键继续...';
    continuePrompt.style.marginTop = '20px';
    continuePrompt.style.fontSize = '16px';
    continuePrompt.style.animation = 'blink 1.5s infinite';
    continuePrompt.className = 'blink';
    resultElement.appendChild(continuePrompt);

    // 添加键盘事件监听
    const handleKeyPress = (e) => {
        resultElement.style.transform = 'translate(-50%, -50%) scale(0.8)';
        resultElement.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(resultElement);
            document.removeEventListener('keydown', handleKeyPress);
            startGame();
        }, 300);
    };

    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyPress);
    
    // 添加触摸事件监听
    document.addEventListener('touchstart', handleKeyPress);
    
    // 添加按钮点击事件监听
    const startButton = document.getElementById('startButton');
    if (startButton) {
        startButton.addEventListener('click', handleKeyPress);
    }
}

// 添加触摸控制支持
function setupTouchControls() {
    // 创建虚拟按钮容器
    const touchControls = document.createElement('div');
    touchControls.id = 'touchControls';
    touchControls.style.position = 'relative';
    touchControls.style.margin = '20px auto';
    touchControls.style.width = '100%';
    touchControls.style.maxWidth = '300px';
    touchControls.style.display = 'flex';
    touchControls.style.justifyContent = 'center';
    touchControls.style.alignItems = 'center';
    touchControls.style.zIndex = '99';

    // 左按钮
    const leftBtn = document.createElement('button');
    leftBtn.textContent = '←';
    leftBtn.style.cssText = `
        width: 60px;
        height: 60px;
        font-size: 18px;
        border-radius: 50%;
        background-color: rgba(76, 175, 80, 0.9);
        color: white;
        border: none;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        transition: all 0.3s ease;
    `;

    // 跳跃按钮
    const jumpBtn = document.createElement('button');
    jumpBtn.textContent = '↑';
    jumpBtn.style.cssText = `
        width: 60px;
        height: 60px;
        font-size: 18px;
        border-radius: 50%;
        background-color: rgba(255, 107, 107, 0.9);
        color: white;
        border: none;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        margin: 0 10px;
        transition: all 0.3s ease;
    `;

    // 右按钮
    const rightBtn = document.createElement('button');
    rightBtn.textContent = '→';
    rightBtn.style.cssText = `
        width: 60px;
        height: 60px;
        font-size: 18px;
        border-radius: 50%;
        background-color: rgba(76, 175, 80, 0.9);
        color: white;
        border: none;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        transition: all 0.3s ease;
    `;

    // 按钮事件
    leftBtn.addEventListener('touchstart', () => keys.left = true);
    leftBtn.addEventListener('touchend', () => keys.left = false);
    leftBtn.addEventListener('mousedown', () => keys.left = true);
    leftBtn.addEventListener('mouseup', () => keys.left = false);

    rightBtn.addEventListener('touchstart', () => keys.right = true);
    rightBtn.addEventListener('touchend', () => keys.right = false);
    rightBtn.addEventListener('mousedown', () => keys.right = true);
    rightBtn.addEventListener('mouseup', () => keys.right = false);

    jumpBtn.addEventListener('touchstart', () => {
        if (!player.isJumping) {
            player.velocityY = -player.jumpPower;
            player.isJumping = true;
            soundEffects.playJumpSound();
        }
    });
    jumpBtn.addEventListener('mousedown', () => {
        if (!player.isJumping) {
            player.velocityY = -player.jumpPower;
            player.isJumping = true;
            soundEffects.playJumpSound();
        }
    });

    // 悬停效果
    leftBtn.addEventListener('mouseover', () => leftBtn.style.transform = 'scale(1.05)');
    leftBtn.addEventListener('mouseout', () => leftBtn.style.transform = 'scale(1)');
    rightBtn.addEventListener('mouseover', () => rightBtn.style.transform = 'scale(1.05)');
    rightBtn.addEventListener('mouseout', () => rightBtn.style.transform = 'scale(1)');
    jumpBtn.addEventListener('mouseover', () => jumpBtn.style.transform = 'scale(1.05)');
    jumpBtn.addEventListener('mouseout', () => jumpBtn.style.transform = 'scale(1)');

    // 添加按钮到容器
    touchControls.appendChild(leftBtn);
    touchControls.appendChild(jumpBtn);
    touchControls.appendChild(rightBtn);

    // 添加到游戏控制区域
    const startButtonContainer = document.getElementById('startButtonContainer');
    if (startButtonContainer) {
        startButtonContainer.parentNode.appendChild(touchControls);
    } else {
        document.body.appendChild(touchControls);
    }
}

// 添加开始按钮事件监听
document.addEventListener('DOMContentLoaded', () => {
    // 初始化触摸控制
    setupTouchControls();
    // 初始化难度
    updateDifficulty();
    
    // 创建开始按钮
    const startButton = document.createElement('button');
    startButton.id = 'startButton';
    startButton.textContent = '开始游戏';
    startButton.style.fontSize = '18px';
    startButton.style.padding = '15px 30px';
    startButton.style.marginTop = '20px';
    startButton.style.backgroundColor = '#4CAF50';
    startButton.style.color = 'white';
    startButton.style.border = 'none';
    startButton.style.borderRadius = '5px';
    startButton.style.cursor = 'pointer';
    startButton.style.zIndex = '100';
    startButton.style.display = 'block';
    startButton.style.margin = '20px auto 0';
    
    // 将按钮添加到指定容器中
    const startButtonContainer = document.getElementById('startButtonContainer');
    startButtonContainer.appendChild(startButton);
    
    // 添加点击事件和游戏状态变量
    let isGameRunning = false;
    startButton.addEventListener('click', () => {
        if (!isGameRunning) {
            startButton.textContent = '停止游戏';
            startGame();
            isGameRunning = true;
        } else {
            startButton.textContent = '开始游戏';
            // 假设存在stopGame函数，如果没有需要实现
            if (typeof stopGame === 'function') {
                stopGame();
            }
            isGameRunning = false;
        }
    });
});